package cn.yunhe.crm.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Servlet Filter implementation class RequestFilter
 */
public class RequestFilter implements Filter {

    /**
     * Default constructor. 
     */
    public RequestFilter() {
       System.out.println("RequestFilter实例化");
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		System.out.println("RequestFilter销毁");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) res;
		
		//如果session不为空，就返回该session,为空则返回null
		HttpSession session=request.getSession(false);
		
		//获取请求的url
		String currentURL = request.getRequestURI();
		//截取到当前文件名用于比较
		String targetURL = currentURL.substring(currentURL.indexOf("/",1),currentURL.length());
		System.out.println(targetURL);
		//判断当前页面是否是重定向后的错误页面,防止死循环
		/*if(session==null){
			if((!"/tologin.do".equals(targetURL))&&(!"/loginout.do".equals(targetURL))&&(!"/login.do".equals(targetURL))){
				response.sendRedirect(request.getContextPath()+"/erro.jsp");
				return;
			}
		}else if((session.getAttribute("user")==null)){
			if((!"/tologin.do".equals(targetURL))&&(!"/login.do".equals(targetURL))&&(!"/loginout.do".equals(targetURL))){
				response.sendRedirect(request.getContextPath()+"/erro.jsp");
				return;
			}
		}*/
		
		if(session==null||session.getAttribute("user")==null){
			if((!"/tologin.do".equals(targetURL))&&(!"/loginout.do".equals(targetURL))&&(!"/login.do".equals(targetURL))
					&&(!"/checkyzm.do".equals(targetURL))){
				response.sendRedirect(request.getContextPath()+"/erro.jsp");
				return;
			}
		}
		
		/*if((!"/tologin.do".equals(targetURL))&&(!"/loginout.do".equals(targetURL))&&(!"/login.do".equals(targetURL))){
			response.sendRedirect(request.getContextPath()+"/erro.jsp");
			return;
		}*/
		chain.doFilter(req, res);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("RequestFilter初始化");
	}

}
